package com.zjx.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjx.reggie.dto.DishDto;
import com.zjx.reggie.entity.Dish;
import com.zjx.reggie.entity.DishFlavor;
import com.zjx.reggie.mapper.DishMapper;
import com.zjx.reggie.service.DishFlavorService;
import com.zjx.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Resource
    private DishFlavorService dishFlavorService;


    @Override
    public void updateFlavor(DishDto dishDto) {
        this.updateById(dishDto);

        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId,dishDto.getId());

        dishFlavorService.remove(qw);

        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setId(null);
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public DishDto getByIdWithFlavor(String id) {
        Dish dish = this.getById(id);

        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        LambdaQueryWrapper<DishFlavor> df = new LambdaQueryWrapper<>();
        df.eq(DishFlavor::getDishId,id);

        List<DishFlavor> flavors= dishFlavorService.list(df);
        dishDto.setFlavors(flavors);
        return  dishDto;
    }

    @Override
    public void saveFlavor(DishDto dishDto) {
        this.save(dishDto);

        String id = dishDto.getId();

        List<DishFlavor> flavors = dishDto.getFlavors();
        for (int i = 0; i < flavors.size(); i++) {
            flavors.get(i).setDishId(id);
        }
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public void delete(List<String> ids) {
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.in(Dish::getId,ids);

        LambdaQueryWrapper<DishFlavor> dfQw = new LambdaQueryWrapper<>();
        dfQw.in(DishFlavor::getDishId,ids);
        this.remove(qw);

        dishFlavorService.remove(dfQw);
    }
}
